package com.opticon.vaadinR.runnable;

import com.opticon.vaadinR.core.RSource;
import com.opticon.vaadinR.core.conf.RCallerConfiguration;
import org.apache.log4j.Logger;
import rcaller.RCaller;

import java.util.Observable;

/**
 * This class is Runnable and will try to run an RSource file at runtime.
 */
public class RRunner extends Observable implements Runnable {

    private static Logger logger = Logger.getLogger(RRunner.class);
    /**
     * The RSourcefile to be executed.
     */
    private RSource iRSource;

    /**
     * A private static Instance to executed R code.
     */
    private static RCaller caller = new RCaller();
    private boolean boolErrorStream = true;
    private boolean boolOutputStream = true;

    /**
     * Creates a new RRunner from an RSource file.
     * @param aRSource
     */
    public RRunner(RSource aRSource) {
        iRSource = aRSource;
        caller.setRScriptExecutableFile(RCallerConfiguration.getRscriptLocation());
    }

    /**
     * Executes the specified RSource file.
     */
    public void run() {
        try {
            // Ex
            String code = iRSource.getCode();
            caller.RunRCode(code, boolErrorStream, boolOutputStream);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            // Forward the error message!
            notifyObservers(e);
        }
    }
}
